#!/usr/bin/python 
# -*- coding: utf-8 -*-
# http://www.redmine.org/projects/redmine/wiki/Rest_Issues

from datetime import datetime
from datetime import timedelta
from time import mktime

import gtk
import dbus
import dbus.service
import dbus.mainloop.glib

from pyactiveresource.activeresource import ActiveResource
import settings


class Issues(ActiveResource):
    _site = settings.SITE
    _user = settings.USER
    _password = settings.PASSWORD


class Versions(ActiveResource):
    _site = settings.SITE
    _user = settings.USER
    _password = settings.PASSWORD


class CalendarService(dbus.service.Object):
    busname = 'org.gnome.Shell.CalendarServer'
    object_path = '/org/gnome/Shell/CalendarServer'

    def __init__(self):
        bus = dbus.service.BusName(self.busname,
                                        bus=dbus.SessionBus(),
                                        replace_existing=True)

        super(CalendarService, self).__init__(bus, self.object_path)
        
        # versions cache
        self.versions = {}

        # issues cache
        self.issues = {}
        

    def _get_versions(self, force_reload):
        if not self.versions or force_reload:
            versions = Versions.find(from_='projects/%s/versions.xml' % settings.PROJECT)
            
            for version in versions:
                self.versions[version.id] = version

        return self.versions
        
        
    def _get_issues(self, since, force_reload):
        if not self.issues.has_key(since) or force_reload:
            issues = Issues.find(start_date='>=%s' % datetime.fromtimestamp(int(since)).strftime('%Y-%m-%d'),
                                 project_id=settings.PROJECT, 
                                 limit=100, 
                                 assigned_to=settings.USER, 
                                 sort='id',
                                 done_ratio='<=80')
            self.issues[since] = issues
            
        return self.issues[since]

 
    @dbus.service.method('org.gnome.Shell.CalendarServer',
                         in_signature='xxb', out_signature='a(sssbxxa{sv})')
    def GetEvents(self, since, until, force_reload):
        print "Getting events...", since, until
        events = []

        versions = self._get_versions(force_reload)
        issues = self._get_issues(since, force_reload)

        for issue in issues:
            wholeday = False
            date_format = "%Y-%m-%d"
            
            print issue.id 
            
            # priority
            pr = str(issue.priority.name)
            
            # 50 => 05:00
            if pr.isdigit():
                hour = int(pr) / 10
                minute = int(pr) % 10
            else:
                hour = 0
                minute = 0
            
            try:
                dstart = datetime.strptime(issue.start_date, date_format)
                dstart = dstart.replace(hour=hour, minute=minute)
                start = int(mktime(dstart.timetuple()))
            except:
                print issue.id, "skipped - no start_date"
                continue

            # version
            try:
                version = versions[issue.fixed_version.id]
                due_date = datetime.strptime(version.due_date, date_format)
            except:
                if issue.due_date is not None:
                    due_date = datetime.strptime(issue.due_date, date_format)
                else:
                    due_date = dstart + timedelta(days=1)
            
            dend = due_date
            end = int(mktime(dend.timetuple()))
            
            # subject
            try:
                if issue.parent.id:
                    subject = '- %s' % issue.subject
                else:
                    subject = issue.subject
            except:
                subject = issue.subject
            
            print issue.id, 
            print subject
            print dstart
            print dend

            events.append((issue.id, 
                           subject, 
                           repr(issue.description), 
                           wholeday,
                           start, 
                           end, 
                           {}))

        return events

if __name__ == '__main__':
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    myservice = CalendarService()
    print myservice
    gtk.main()
